package com.yzk.aigy.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzk.aigy.common.OssTemplate;
import com.yzk.aigy.mapper.SysMovieMapper;
import com.yzk.aigy.model.system.SysMovie;
import com.yzk.aigy.model.vo.UpdateMovieVo;
import com.yzk.aigy.service.SysMovieService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
* @description 针对表【sys_movie】的数据库操作Service实现
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class SysMovieServiceImpl extends ServiceImpl<SysMovieMapper, SysMovie>
    implements SysMovieService{

    private final OssTemplate ossTemplate;

    @Override
    public Boolean updateMovie(UpdateMovieVo updateMovieVo) {
        int row = baseMapper.updateById(updateMovieVo);
        if (row == 0) return false;
        if (StringUtils.hasText(updateMovieVo.getOldFileName())) {
            String fileName = updateMovieVo.getOldFileName().substring(updateMovieVo.getOldFileName().indexOf("images"));
            ossTemplate.delFile(fileName);
            log.info("更新影视，删除旧文件：{}", fileName);
        }
        return true;
    }

    @Override
    public Boolean removeMovieById(Long id) {
        SysMovie sysMovie = baseMapper.selectOne(Wrappers.<SysMovie>lambdaQuery().select(SysMovie::getImage).eq(SysMovie::getId, id));
        int row = baseMapper.deleteById(id);
        if (row == 0) return false;
        String fileName = sysMovie.getImage().substring(sysMovie.getImage().indexOf("images"));
        ossTemplate.delFile(fileName);
        log.info("移除影视，删除文件：{}", fileName);
        return true;
    }

    @Override
    public Boolean removeMovieByIds(List<Long> ids) {
        // 获取需要删除的影视图片地址
        List<SysMovie> sysMovies = baseMapper.selectList(Wrappers.<SysMovie>lambdaQuery().select(SysMovie::getImage).in(SysMovie::getId, ids));
        List<String> images = sysMovies.stream().map(SysMovie::getImage).collect(Collectors.toList());
        int row = baseMapper.deleteBatchIds(ids);
        if (row == 0) return false;
        StringBuilder stringBuilder = new StringBuilder(17 * ids.size());
        stringBuilder.append(" -> { ");
        for (String image : images) {
            String fileName = image.substring(image.indexOf("images"));
            ossTemplate.delFile(fileName);
            stringBuilder.append(fileName).append(" ");
        }
        log.info("移除影视，删除文件{}", stringBuilder.append("}"));
        return true;
    }

}




